package utilities;

import gui.VPOfOperations.VPOfOperationsReports;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Services
{
/**
 * This method converts ArrayList to ByteArray
 * @param message array list to covnert
 * @return converted Byte[]
 */
	public static byte[] convertArrayListToByteArray (Object message)
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out = null;
		try
		{
			out = new ObjectOutputStream(bos);
			out.writeObject(message);
		  byte[] byteArray = bos.toByteArray();
		  if (out != null)
		  {
		      out.close();
		  }
		  try
		  {
			  bos.close();
		  }
		  catch (IOException ex)
			{}	
		  
		  return byteArray; // Convertion completed
		}
		catch (IOException ex)
		{}	
			
		 // If we got here we failed to convert the Object to a byte[]
		
		byte[] failed = new byte[0]; 
		
		return failed;
	
	}
	
/**
 * This method converts a ByteArray to ArrayList	
 * @param message Byte[] to convert
 * @return converted ArrayList
 */
	@SuppressWarnings("unchecked")
	public static ArrayList<Object> convertByteArrayToArrayList (byte[] message)
	{
		ByteArrayInputStream bis = new ByteArrayInputStream(message);
		ObjectInput in = null;
		
		  try
		  {
			in = new ObjectInputStream(bis);
			try 
			{
				Object obj = in.readObject();
				
				try {
				    bis.close();
				  } catch (IOException ex) {
				    // ignore close exception
				  }
				
				try {
				    if (in != null) {
				      in.close();
				    }
				  } catch (IOException ex) {
				    // ignore close exception
				  }
				
				return (ArrayList<Object>)obj;
				
				
			} catch (ClassNotFoundException e)
			{
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			
		}
		  catch (IOException ex) {
		    // ignore close exception
		  }
		  
		  // If we got here, we failed to convert the message
		  
		  ArrayList<Object> failed = new ArrayList<Object>();
		  failed.add("failedToConvert");
		  
		  return failed;
		  
		
	}
	
	
	
/**
 * This method checks if an input is a character or not .	
 * @param str string to check
 * @return boolean true or false
 */
	public static boolean isNumeric(String str)
	{
		if (str.equals(""))
			return false;
		else
		{
			NumberFormat formatter = NumberFormat.getInstance();
			  ParsePosition pos = new ParsePosition(0);
			  formatter.parse(str, pos);
			  return str.length() == pos.getIndex();
		}
	  
	}
	
	
   /**
    * converts a string to an item
    * @param item string
    * @return object
    */
	 public static Object createObject (final String item) 
	 {
	        return new Object()
	        {
	        	public String toString()
	        	{
	        		return item;
	        	}
	        	
	      	};
	 }
	 
	
	 
/**
 * This method converts a type and returns it's family .	 
 * @param type string
 * @return family the type belongs to as a string
 */
	 public static String convertTypeToFamily ( String type)
	 {
		 if (type.equalsIgnoreCase("ABB3") || type.equalsIgnoreCase("ANCHOR") || type.equalsIgnoreCase("BAL15") || type.equalsIgnoreCase("BAL65") || type.equalsIgnoreCase("BAL-65") ||  type.equalsIgnoreCase("OPAB130") || type.equalsIgnoreCase("OPAB135") || type.equalsIgnoreCase("OPAB16") || type.equalsIgnoreCase("OPAB19") || type.equalsIgnoreCase("RING2") ||  type.equalsIgnoreCase("RING") )
			 return ("PMMA");
		 else
		 if (type.equalsIgnoreCase("BLENS") || type.equalsIgnoreCase("BUNNYLENS") || type.equalsIgnoreCase("BNYLENS") || type.equalsIgnoreCase("SEELENS") || type.equalsIgnoreCase("BAL-65") ||  type.equalsIgnoreCase("SEELENSAF") || type.equalsIgnoreCase("BNYAFEZ") || type.equalsIgnoreCase("BNYAF") || type.equalsIgnoreCase("SLENSAFEZ") || type.equalsIgnoreCase("SLENSAF") ||  type.equalsIgnoreCase("BNYMFEZ") ||  type.equalsIgnoreCase("BNYMF") ||  type.equalsIgnoreCase("SLENSMFEZ") ||  type.equalsIgnoreCase("SLENSMF") ||  type.equalsIgnoreCase("SEELENSMF") ||  type.equalsIgnoreCase("BUNNYMF") ||  type.equalsIgnoreCase("BNYTR/VISTOR") ||  type.equalsIgnoreCase("BNYTR") ||  type.equalsIgnoreCase("VISTOR") )
			 return ("Hydrophilic");				 
		 else
         if (type.equalsIgnoreCase("SEELENSHP") || type.equalsIgnoreCase("SLENSHP") || type.equalsIgnoreCase("BUNNYHP") || type.equalsIgnoreCase("BUNYHP") || type.equalsIgnoreCase("ETOSEELENSHP") ||  type.equalsIgnoreCase("ETOBUNNYHP") )
			 return ("Hydrophobic");
         else
         if (type.equalsIgnoreCase("Presbia"))
        	 return ("Presbia");
         else
        	 return ("Unknown");			 
	 }
	 
/**
 *This method returns the Date of today in dd/MM/yyyy format 
 * @return today
 */
	 public static String getToday()
	 {
		 Date todayCalendar;
		 String today;
		 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		 
		 todayCalendar = Calendar.getInstance().getTime();
		 today = dateFormat.format(todayCalendar);
		 
		 return today;
		 
	 }
	 
	 /**
	  * 
	  * @return today in dd-MM-yyyy foramt
	  */
	 public static String getTodayDifferentFormat()
	 {
		 Date todayCalendar;
		 String today;
		 DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		 
		 todayCalendar = Calendar.getInstance().getTime();
		 today = dateFormat.format(todayCalendar);
		 
		 return today;
		 
	 }

	 /**
	  * 
	  * @return today in yyyy-MM-dd format
	  */
	 public static String getTodayDifferentFormat2()
	 {
		 Date todayCalendar;
		 String today;
		 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		 
		 todayCalendar = Calendar.getInstance().getTime();
		 today = dateFormat.format(todayCalendar);
		 
		 return today;
		 
	 }
	 
	 /**
	  * exports a table into an excel file
	  * @param table table to export
	  * @return validity string
	  */
	public static ArrayList<Object> exportToExcel(JTable table)
	{
		ArrayList<Object> response = new ArrayList<Object>();
		try
		{
			String report = "report_number_" + (VPOfOperationsReports.reportCounter-1) + "_" + utilities.Services.getTodayDifferentFormat() + ".xlsx";
			String filename = "./Reports/" + report;
			utilities.ExcelWriter.CreateExlFile(filename);
			utilities.ExcelWriter.writeToExcell(table, filename);
			response.add(true);
			response.add(report);
			
		}
		catch (FileNotFoundException e1) 
		{
			
			
			e1.printStackTrace();
			response.add(false);
		} 
		catch (IOException e1)
		{
			
			
			e1.printStackTrace();
			response.add(false);
		}
		
		return response;
	}

	/**
	 * Parses data from Custom pivot table models to normal JTable models
	 * @param myTable Custom pivot table
	 * @return Standartized Jtable
	 */
	public static JTable parsePivotTableToJTrable(JTable myTable) 
	{
		JTable table = new JTable();
		
		ArrayList<String> columns = new ArrayList<String>();
		for (int j=0 ; j<myTable.getColumnCount();j++)
		{
			//System.out.println(myTable.getValueAt(0,j));
			columns.add((String) myTable.getValueAt(0,j));
		}
		
		String[] columnStrings = new String[columns.size()];
		columnStrings =	columns.toArray(columnStrings);
		table.setModel(new DefaultTableModel(
				new Object[][] {
				},
				columnStrings
			));
		
		
		for (int i=1; i<myTable.getRowCount();i++)
		{
			ArrayList<Object> row = new ArrayList<Object>();
			
			for (int j=0 ; j<myTable.getColumnCount();j++)
			{
				String value;
				try
				{
					value = (String) myTable.getValueAt(i, j) + " ";
					if (value.equalsIgnoreCase("null "))
			        	row.add("0");
			        else
			        	if (value.equalsIgnoreCase(" "))
				        	row.add("0");
			        	else
			        	row.add(value);
				}
				catch (ClassCastException e1)
				{
					Number numberValue;
					
					numberValue = (Number) myTable.getValueAt(i, j);
					row.add(numberValue);
					
				}		
			}
			
			// add row
			Object[] rowFromArray = new Object[row.size()];
			rowFromArray = row.toArray(rowFromArray);
			 ((DefaultTableModel) table.getModel()).addRow(rowFromArray);
			
		}
		
		return table;
		
		
	}

	/**
	 * 
	 * @return the date 60 days ago
	 */
	public static java.lang.String getTwoMonthsAgo()
	{
		 Calendar twoMonthsAgoCalendar;
		 Date twoMonthsAgo;
		 String twomonths;
		 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		 
		 twoMonthsAgoCalendar = Calendar.getInstance();
		 twoMonthsAgoCalendar.add(Calendar.MONTH, -2);
		 twoMonthsAgo=twoMonthsAgoCalendar.getTime();
		 
				 
		 twomonths = dateFormat.format(twoMonthsAgo);
		 
		 return twomonths;
	}
}
